package com.student.advice;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.student.entity.AopLog;
import com.student.entity.Student;
import com.student.mapper.AopLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
  import java.util.Date;

@Aspect//aop日志
@Component
public class LogAspect {

    @Resource
    private AopLogMapper aopLogMapper;

    @Resource
    private HttpServletRequest request;

    @Pointcut("execution(* com.student.service..*.*(..))")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();

        // 执行方法
        Object result = point.proceed();


        // 保存日志
        saveSysLog(point, result);

        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint,  Object result) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        AopLog aopLog = new AopLog();

        aopLog.setMethodName(signature.getMethod().getName());
        aopLog.setEventName("方法调用");


        try {
            aopLog.setResult(JSON.toJSONString(result));
        } catch (Exception e) {
            aopLog.setResult("结果解析失败");
        }

        aopLog.setUsername(getUsername());
        aopLog.setCreateTime(new Date());

        aopLogMapper.insert(aopLog);
    }

    private String getUsername() {
        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("loginUser");

        if (null != student) {
            return student.getSname();
        } else {
            return null;
        }
    }
}
